package study.java.jdk.jdk8._1_stream.parallel;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * ParallelStreams 注意事项
 * （1）使用并行流时，不要使用 collectors.groupingBy,collectors.toMap，替代为
 * collectors.groupingByConcurrent , collectors.toConcurrentMap，或直接使用串行流。
 */
@Slf4j
public class _3_parallel_Test {

    private List<String> userIdLt = Arrays.asList("9001",
            "9002",
            "9003",
            "9004",
            "9005",
            "9006");

    @Test
    public void test1() {
        List<UserClient.UserData> userLt = UserClient.getUserLt(userIdLt);
        log.info("{}", userLt);
    }

    @Test
    public void test2() {
        //分片
        List<List<String>> userIdLts = Lists.partition(userIdLt, 2);
        //并行执行
        List<List<UserClient.UserData>> userLts = userIdLts.parallelStream()
                .map(userId -> UserClient.getUserLt(userId))
                .collect(Collectors.toList());
        //扁平
        List<UserClient.UserData> userLt = userLts.stream()
                .flatMap(List::stream)
                .collect(Collectors.toList());
        log.info("{}", userLt);
    }

    @Test
    public void test4() {
        Map<String, UserClient.UserData> userMap = Lists.partition(userIdLt, 2).parallelStream()
                .map(e -> UserClient.getUserLt(e))
                .flatMap(List::stream)
                .collect(Collectors.toMap(UserClient.UserData::getUserId, Function.identity()));
        log.info("{}", userMap);
    }
}
